

#include <stdio.h>
#include <string.h>
#include <libsoup/soup.h>
#include "xhttp_str.h"
#include "xm_log.h"

struct xhttp_str_st{
    SoupSession * session;
};

struct xhttp_req{
    xhttp_str_t obj;
    xhttp_str_callback_t callback;
    void * cbcontext;
    SoupMessage * msg;
};

static
void soup_http_msg_callback (SoupSession *session,
                             SoupMessage *msg,
                             gpointer user_data){
    xhttp_req * req = (xhttp_req *) user_data;
    //    dump_soup_msg(req->msg);

    if(req->callback){
        soup_message_get_uri(msg);
        req->callback(req->obj, req->cbcontext, req->msg->status_code, msg->response_body->data, msg->response_body->length, msg);
    }
    
    g_slice_free(struct xhttp_req, req);
}


xhttp_str_t xhttp_str_create(){
    xhttp_str_t obj = (xhttp_str_t) g_slice_alloc0(sizeof(xhttp_str_st));
    obj->session = soup_session_sync_new();
    return obj;
}

void xhttp_str_delete(xhttp_str_t obj){
    if(!obj) return;
    if(obj->session){
        g_object_ref (obj->session);
        obj->session = NULL;
    }
    
    g_slice_free(struct xhttp_str_st, obj);
}


int xhttp_str_post_json(xhttp_str_t obj, const char * url, const char * json, int json_length
                        , xhttp_str_callback_t callback, void * cbcontext){
    xhttp_req * req = (xhttp_req *) g_slice_alloc0(sizeof(xhttp_req));
    req->msg = soup_message_new ("POST", url);
    req->obj = obj;
    req->callback = callback;
    req->cbcontext = cbcontext;
    
    soup_message_set_request (req->msg, "application/json", SOUP_MEMORY_COPY,
                              json, json_length);
    soup_session_queue_message (obj->session, req->msg, soup_http_msg_callback, req);
    g_object_ref (req->msg);
//    gdbgi("soup message queued");
    return 0;
}

const char *xhttp_str_msg_path(xhttp_str_msg_t m){
    SoupMessage * msg = (SoupMessage *) m;
    return soup_uri_get_path(soup_message_get_uri(msg));
}

static
void test_xhttp_str_callback(xhttp_str_t obj, void * cbcontext, int status_code, const char * response, int response_length, xhttp_str_msg_t msg){
    gdbgi("cbcontext=%s", (const char *)cbcontext);
    gdbgi("status_code=%d", status_code);
    gdbgi("response_length=%d", response_length);
    gdbgi("response=%p, [%s]", response, response?response:"null");
}

void test_xhttp_str(){
    const char * url = "http://localhost:1880/";
    const char * json = "{\"op\":\"pingC\"}";
    int json_length = strlen(json);
    
    xhttp_str_t obj = xhttp_str_create();
    xhttp_str_post_json(obj, url, json, json_length, test_xhttp_str_callback, (void *)"cbcontext");
    xhttp_str_delete(obj);
}
